import React,{Component} from "react";
import {Input, Form, message, Button, BackTop, Pagination,Modal } from 'antd';
import Header from "../component/header.js";
import Footer from "../component/footer.js";
import moment from "moment";
import ajax from "../ajaxMethod";
import '../assets/stylesheets/detail/comments.css'

const format = "YYYY-MM-DD HH:mm";

class Comments extends Component{
    constructor(props){
        super(props);
        this.state = {
            values:{
                type:0,
                page:1,
                total:0,
                pageSize:20,
                data:[],
                like:[],//对应每条评论用户是否点赞过
            },
            sort: 0,//0是按时间排，1是按热度排序
            ModalVisible:false,
        }
    }
    componentDidMount(){
        scrollTo(0,0);
        this.getData();
    }
    
    getData = (sort, page) =>{
        let _this = this,
            nowSort = this.state.sort,
            nowPage = page || this.state.values.page;
        
        if(sort !== undefined){ nowSort = sort; }
        if(page !== undefined){ nowPage = page; }
        console.log("fasng", {sort: nowSort, page : nowPage, pageSize: this.state.values.pageSize, username: localStorage.getItem("username")});
        ajax.getAjax("/interface/comments",{sort: nowSort, page : nowPage, pageSize: this.state.values.pageSize, username: localStorage.getItem("username")},res=>{
            if(res.success){
                console.log("res-----------", res);
                _this.setState({values:{...this.state.values, ...res.data, page: nowPage}, sort: nowSort});
            }else{
                console.error(success.description);
            }
        }, err=>{
            console.error(err);
        })
    }
    //改变排序方式
    changeSort = (e) =>{
        if(e.target.children.length === 0){
            //当点击的是不一样的排序的时候才重新查询
            if(e.target.getAttribute("data-sort") === "0"){
                this.state.sort === 1?this.getData(0):"";
            }else{
                this.state.sort === 0?this.getData(1):"";
            }
        }
    }
    onPageChange = (page) =>{
        console.log("pagechange", page);
        this.getData(this.state.sort, page);
    }
    commentsSubmit = (e) =>{
        this.submit();
        e.preventDefault();
    }
    onKeyPress = (e) =>{
        if(e.nativeEvent.keyCode === 13){ //e.nativeEvent获取原生的事件对像
            this.submit();
        }
    }
    handleOk = () =>{
        this.props.history.push({pathname:"/login"});
        this.setState({ModalVisible:false});
    }
    handleCancel = () =>{
        this.setState({ModalVisible:false});
    }
    submit = () =>{
        let values = this.props.form.getFieldsValue(),
            username = localStorage.getItem("username"),
            comment = values.comment.replace(/\s+/g, ""),
            _this = this;

        if(username){//用户已经登陆
            if(comment){
                ajax.postAjax("/interface/comments",{comment: comment, username: username}, res=>{
                    if(res.success){
                        message.success("提交成功");
                        window.location.reload();
                    }else{
                        console.error(res.description);
                    }
                },err=>{
                    message.error("后台出错");
                    console.error(err);
                })
            }else{
                message.info("请输入内容再提交");
            }
        }else{//未登录
            this.setState({ModalVisible:true});
        }
        this.props.form.resetFields();
    }
    likeClick(i){
        console.log('点赞第i跳数据');
        let _this = this, username = localStorage.getItem("username");
        if(username){//用户登录了才能点赞
            if(this.state.values.like[i]){//取消点赞
                ajax.postAjax("/interface/commentsDislike",{id: this.state.values.data[i]._id, username:username },res=>{
                    if(res.success){
                        _this.setState({values:{..._this.state.values,like:(()=>{
                            let nowlike = _this.state.values.like;
                            nowlike[i] = false;
                            return nowlike;
                        })(),data:(()=>{
                            let nowdata = _this.state.values.data;
                            nowdata[i].like -= 1;
                            return nowdata;
                        })()}})
                    }else{
                        console.error(res.description);
                    }
                },err=>{
                    console.error(err);
                })
            }else{//点赞
                ajax.postAjax("/interface/commentsLike",{id: this.state.values.data[i]._id, username:username },res=>{
                    if(res.success){
                        _this.setState({values:{..._this.state.values,like:(()=>{
                            let nowlike = _this.state.values.like;
                            nowlike[i] = true;
                            return nowlike;
                        })(),data:(()=>{
                            let nowdata = _this.state.values.data;
                            nowdata[i].like += 1;
                            return nowdata;
                        })()}})
                    }else{
                        console.error(res.description);
                    }
                },err=>{
                    console.error(err);
                })
            }
        }else{//没登陆提示登录
            this.setState({ModalVisible:true});
        }
    }
    render(){
        const {getFieldProps} = this.props.form;
        const state = this.state;
        return(
        <div className="comments">
            <Header></Header>
            <div className="head-contain"></div>
            <div className="input-wrap">
                <p>发表留言:</p>
                <Form onSubmit={this.commentsSubmit}>
                    <Form.Item>
                        <Input.TextArea 
                            onKeyPress={this.onKeyPress}
                            maxLength={500}
                            placeholder="请输入留言，最多500字，请自觉遵守互联网相关的政策法规，严禁发布色情、暴力、反动的言论。"
                            {...getFieldProps("comment",{rules:[], initalValue:""})}
                            style={{minHeight:"100px", maxHeight:"300px"}}
                        ></Input.TextArea>
                    </Form.Item>
                    <Button type="primary" htmlType="submit">发 表</Button>
                </Form>
            </div>
            <div className="sort-pagination">
                <ul className='sort' onClick={this.changeSort}>
                    <li data-sort="0" data-selected={state.sort?"false":"true"}>按时间排序</li>
                    <li data-sort="1" data-selected={state.sort?"true":"false"}>按热度排序</li>
                </ul>
                <Pagination className="page" showQuickJumper current={state.values.page} pageSize={state.values.pageSize} total={state.values.total} onChange={this.onPageChange}>></Pagination>
            </div>
            <div className="content-box">
                {
                    (()=>{
                        let arr = [];
                        state.values.data.map((item, i, data)=>{
                            arr.push(
                                <div className="comment-item">
                                    <p className="user">{item.username}</p>
                                    <p className="text">{item.comment}</p>
                                    <div className="info">
                                        <span className="time">{moment(item.date).format(format)}</span>
                                        {
                                            state.values.like[i]? <i className='like liked' onClick={this.likeClick.bind(this, i)}></i>: <i className='like' onClick={this.likeClick.bind(this, i)}></i>
                                        }
                                        <span>{item.like}</span>
                                    </div>
                                </div>
                            )
                        })
                        return arr;
                    })()
                }
            </div>
            <div className="pagination">
                <Pagination className="page" showQuickJumper current={state.values.page} pageSize={state.values.pageSize} total={state.values.total} onChange={this.onPageChange}>></Pagination>
            </div>
            <Modal title="提示" 
                wrapClassName="vertical-center-modal"
                visible={this.state.ModalVisible} 
                onCancel={this.handleCancel}
                footer={[
                    <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>去登录</Button>,
                    <Button key="back" type="ghost" onClick={this.handleCancel}>取 消</Button>,
                ]}
            >
                <p>请登陆后再点赞</p>
            </Modal>
            <BackTop />
            <Footer></Footer>
        </div>)
    }
}


export default Form.create({})(Comments);